package com.fastloan.mgt.application.contract.controller;

import com.alibaba.fastjson.JSON;
import com.fastloan.common.model.CheckResult;
import com.fastloan.core.apiauth.base.service.impl.ry.RYEncryptMode;
import com.fastloan.core.apiauth.base.service.impl.ry.model.RYRequestParam;
import com.fastloan.core.apiauth.service.EncryptUtil;
import com.fastloan.mgt.application.base.enums.ApplicationStatusEnum;
import com.fastloan.mgt.application.base.model.Application;
import com.fastloan.mgt.application.base.service.ApplicationService;
import com.fastloan.mgt.application.contract.dao.ApplicationLoanResultMapper;
import com.fastloan.mgt.application.contract.enums.LoanModeEnum;
import com.fastloan.mgt.application.contract.model.ApplicationContract;
import com.fastloan.mgt.application.contract.model.ApplicationLoanResult;
import com.fastloan.mgt.application.contract.service.ApplicationContractService;
import com.fastloan.mgt.application.contract.service.impl.loanmode.mode.ry.model.RyLoanResult;
import com.fastloan.mgt.verify.model.ApiResult;
import com.fastloan.mgt.verify.util.ApiUtil;
import com.fastloan.utils.DateTimeUtil;
import com.fastloan.utils.PropertiesUtil;
import com.kawins.base.baseabs.BaseController;
import com.kawins.result.ResultEnum;
import com.kawins.result.ResultTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

import static com.fastloan.utils.DateTimeUtil.DIGIT_DATETIME_PATTERN;

/**
 * @author yanwe
 * createTime 2017-11-2017/11/11 16:36
 */
@RestController
@RequestMapping("/api/application/contract")
public class ApplicationContractController extends BaseController<ApplicationContract> {

    @Autowired
    private ApplicationContractService applicationContractService;

    @Autowired
    private ApplicationService applicationService;

    @PostMapping()
    public ResultTo contract(ApplicationContract applicationContract
            , @RequestPart(value = "contractFiles",required = false) MultipartFile[] contractFiles) {
        CheckResult checkResult = applicationContractService.contract(applicationContract, contractFiles);
        return checkResult.isCheckResult() ? new ResultTo() :
                new ResultTo(ResultEnum.OPERATION_FAILED,checkResult.getCheckMsg());
    }

    @GetMapping("/applicationInfo/{applicationId}")
    public ResultTo dataPage(@PathVariable("applicationId") String applicationId) {
        return new ResultTo().setData(applicationContractService.getApplicationVo(applicationId));
    }

    @GetMapping("/reject/{applicationId}")
    public ResultTo rejectContract(@PathVariable("applicationId") String applicationId) {
        applicationContractService.rejectContract(applicationId);
        return new ResultTo();
    }

    @GetMapping("/{applicationId}")
    public ResultTo getContractInfo(@PathVariable("applicationId") String applicationId) {
        ApplicationContract contractInfo = applicationContractService.getContractInfo(applicationId);
        if (contractInfo == null){
            Application application = applicationService.selectByPrimaryKey(applicationId);
            if (ApplicationStatusEnum.SIGNED_REJECT
                    .equals(ApplicationStatusEnum.getByType(application.getApplicationStatus()))){
                return new ResultTo(ResultEnum.OPERATION_FAILED,"该进件已被拒绝签约！");
            }
        }
        return new ResultTo().setData(contractInfo);
    }

    @GetMapping("/customer/{applicationId}")
    public ResultTo agreeContract(@PathVariable("applicationId") String applicationId
            , @RequestParam(value = "agree") boolean agree) {
        CheckResult checkResult = applicationContractService.agreeContract(applicationId,agree);
        if (!checkResult.isCheckResult()){
            return new ResultTo(ResultEnum.OPERATION_FAILED,checkResult.getCheckMsg());
        }
        return new ResultTo();
    }

    @Autowired
    private ApplicationLoanResultMapper applicationLoanResultMapper;

    /**
     * 模拟放款
     *
     * @param applicationId 进件ID
     * @param result 放款结果 1 成功 2  失败 3 拒绝
     * @return 结果
     */
    @GetMapping("/loan/{applicationId}/{result}")
    public ResultTo mockLoan(@PathVariable("applicationId") String applicationId,@PathVariable("result")Integer result) {
        ApplicationLoanResult applicationLoanResult = applicationLoanResultMapper.selectByPrimaryKey(applicationId);
        LoanBean loanBean = new LoanBean();
        loanBean.setAgent_order_no(applicationId);
        loanBean.setOrder_no(applicationLoanResult.getLoanNo());
        loanBean.setCode(0);
        switch (result){
            case 1:
                loanBean.setMsg("放款成功");
                break;
            case 2:
                loanBean.setMsg("放款失败");
                break;
            case 3:
                loanBean.setMsg("审核拒绝");
                break;
            default:
                break;
        }
        loanBean.setRemit_result(result);
        loanBean.setRemit_time(DateTimeUtil.format(new Date(),DateTimeUtil.DIGIT_DATETIME_PATTERN));
        RYEncryptMode ryEncryptMode = new RYEncryptMode();
        ryEncryptMode.setRsaPriKey(
                "MIICXAIBAAKBgQCbdcFfZzdoKcM15LrmbYsOWWEFlDW+88SVteVpz1q/k3aEzbdH" +
                "L5XVFIIBRTJpUY+0rFtrbOsatGW3dLC5PJjDorVH80EPXwb7fSmK0a1la0sykFXx" +
                "gToYDb5CWNX5DpxXxFKGq1a/yQjDuZB4P7S2/ozcQqw0H15m5LGZIPoopwIDAQAB" +
                "AoGAN4TVW2n0Oqn3gk6+hL6IU8aNxL1KeHh8M28zkBcydIqIYCNLmgufeeqKB0Qc" +
                "Hcq4BLEtMO9EA1R7own0dyLx9xHFEEOWPKayzfj0xBmJMM++1QqYRTM4QnV5mtzB" +
                "daMTuZGOqqMLnHwfw/pZ4kuv+cqb+vIthlO+AXs8o7kDD7kCQQD8BMC/6KhAwF75" +
                "8rlfXDSoqi6I3Dm/+GS+gbIDaITjBA6xMl1RKpRQ4KcHmoCfNcnLO0WcKpDlHp8R" +
                "fGznWJdNAkEAnep8wj4d2K8xDQttWePJVTMokV2FtX5SSGvujydnUsrHQuvgZmjF" +
                "QhljfpZaRN3ZzSEHhCVASrqTwh8ZxBANwwJBANOYZgF7JTFgkx3HFq8jKq9mW7Xb" +
                "Ob2dn3B4Um8cJV65vGA4ijMozehuBq+SoGWMcsZpGJP7BTbqE+JJluJS9o0CQGel" +
                "Lbk3l9NOOP180Iq9DLmU2D2Aim+yt0K9RFhE3nXijaIIusG8ZiuaCkldWWX1zivq" +
                "T8qVwHrLtoskan7aoo0CQGVL7Q3n8HWdNbaMht+Z+3Bbq98aUvUIhihvbSPQpYZL" +
                "0heGISTGeSiCQPw0FDAuiiPhGb33GuelOm2X0PkuaiM=");
        String data = ryEncryptMode.encryptBeanByRsaPri(loanBean, "tCsAztyqmj37xPb3SXH2PzHSyKJCqZkC");
        RYRequestParam ryRequestParam = new RYRequestParam();
        ryRequestParam.setSc(ryEncryptMode.getEncryptAesKey());
        ryRequestParam.setIv(ryEncryptMode.getAesIv());
        ryRequestParam.setData(data);
        ApiResult apiResult = ApiUtil.sendJsonSync(JSON.toJSONString(ryRequestParam)
                , PropertiesUtil.getProperty("loan.notify"));
        return new ResultTo().setData(apiResult);
    }
}
